package cn.edu.swu.miniwebsvr.core;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class HttpParser {
    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        // TODO: [222024321072045/谢冈兵]
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        //解析请求行
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("Empty request");
        }

        String[] requestParts = requestLine.split(" ");
        if (requestParts.length < 2) {
            throw new IOException("Invalid request line: " + requestLine);
        }

        String method = requestParts[0];
        String fullUrl = requestParts[1];
        parameter.setMethod(method);

        //解析 URL 和查询参数
        String[] urlParts = fullUrl.split("\\?", 2);
        String url = urlParts[0];
        parameter.setUrl(url);

        if (urlParts.length > 1) {
            parseQueryParameters(urlParts[1], parameter);
        }

        //解析请求头
        String headerLine;
        int contentLength = 0;
        String contentType = "";
        while ((headerLine = reader.readLine()) != null && !headerLine.isEmpty()) {
            String[] headerParts = headerLine.split(":", 2);
            if (headerParts.length == 2) {
                String headerName = headerParts[0].trim();
                String headerValue = headerParts[1].trim();
                parameter.addHeader(headerName, headerValue);

                if ("Content-Length".equalsIgnoreCase(headerName)) {
                    try {
                        contentLength = Integer.parseInt(headerValue);
                    } catch (NumberFormatException e) {
                        System.err.println("Invalid Content-Length: " + headerValue);
                    }
                } else if ("Content-Type".equalsIgnoreCase(headerName)) {
                    contentType = headerValue;
                }
            }
        }

        //解析POST请求体
        if ("POST".equalsIgnoreCase(method) && contentLength > 0) {
            char[] bodyChars = new char[contentLength];
            int totalRead = 0;
            while (totalRead < contentLength) {
                int read = reader.read(bodyChars, totalRead, contentLength - totalRead);
                if (read == -1) break;
                totalRead += read;
            }

            if (totalRead > 0) {
                String body = new String(bodyChars, 0, totalRead);
                if (contentType.contains("application/x-www-form-urlencoded")) {
                    parseQueryParameters(body, parameter);
                }
            }
        }
        return parameter;
    }
    private static void parseQueryParameters(String queryString, Parameter parameter) {
        if (queryString == null || queryString.isEmpty()) {
            return;
        }

        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length >= 1) {
                try {
                    String key = URLDecoder.decode(keyValue[0], StandardCharsets.UTF_8.name());
                    String value = keyValue.length > 1 ?
                            URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8.name()) : "";

                    if (parameter.getMethod().equalsIgnoreCase("POST")) {
                        parameter.addBodyParam(key, value);
                    } else {
                        parameter.addUrlParam(key, value);
                    }
                } catch (Exception e) {
                    System.err.println("Error decoding parameter: " + e.getMessage());
                }
            }
        }
    }
}
